package com.bugstack.infrastructure.adapter.repository;

import com.bugstack.domain.task.model.entity.TaskEntity;
import com.bugstack.domain.task.repository.ITaskRepository;
import com.bugstack.infrastructure.event.EventPublisher;
import com.bugstack.infrastructure.dao.ITaskDao;
import com.bugstack.infrastructure.dao.po.Task;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: czb
 * @Description: TODO
 * @DateTime: 2025/3/28 17:30
 **/
@Repository
public class TaskRepository implements ITaskRepository {

    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;

    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<Task> tasks = taskDao.queryNoSendMessageTaskList();
        return tasks.stream().map(task -> {
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(task.getUserId());
            taskEntity.setTopic(task.getTopic());
            taskEntity.setMessageId(task.getMessageId());
            taskEntity.setMessage(task.getMessage());
            return taskEntity;
        }).collect(Collectors.toList());
    }

    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        Task req = new Task();
        req.setUserId(userId);
        req.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(req);
    }

    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        Task req = new Task();
        req.setUserId(userId);
        req.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(req);
    }
}
